import store from './store.js' 


const token = uni.getStorageSync('token');//token
const api = store.state.globalApi;//请求域名
const updateApi = store.state.globalupApi; // 上传文件地址
const authentication = store.state.requestHeader;//token key


/**
 * uni.request封装
 */
export const request = (options) => {
	return new Promise((resolve, reject) => {
		if(!options.url){
			throw new Error("请传入URL!");
			return;
		}
		if(!options.method){
			console.warn(options.url + "未传入请求方式,默认为POST");
		}
		uni.request({
			url: api + options.url,
			method: options.method || 'POST',
			data: options.data || '',
			header: {
				"Content-Type": store.state.requestHeader,
				token : token
			},
			success: (res) => {
				if(res.statusCode < 500 ){
					console.log(res.data);
					resolve(res.data);
				}else{
					throw new Error("服务器错误,请检查");
					console.error(res);
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '请求失败'
				})
				reject(err)
			}
		})
	})
}
/**
 * 上传图片 阿里oss方式  小程序
 */
export const uploadImageApplet = (event) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token')
		var pathList = [];
		uni.chooseImage({
			count: event.count || 9,
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				uni.showLoading({
					title: '上传中'
				})
				let obj = new Date()
				let day = obj.getDate()
				let month = obj.getMonth() + 1
				let year = obj.getFullYear()
				for (let i = 0; i < tempFilePaths.length; i++) {
					let index = tempFilePaths[i].lastIndexOf(".")
					let suffix = tempFilePaths[i].substr(index + 1)
					let fileList = uni.getStorageSync('user').id + '/' + Math.random().toString(36).substr(2) +
						'.' + suffix
					uni.request({
							url: api + 'oss_getSign',
							data: {
								token: token
							},
							method: 'POST',
							header: {
								"Content-Type": store.state.requestHeader,
								authentication : token
							},
						})
						.then((res) => {
							uni.uploadFile({
								url: store.state.globalupApi,
								filePath: tempFilePaths[i],
								name: event.name ? event.name : 'file',
								formData: {
									'key': fileList,
									'policy': res[1].data.data.policy, // 输入你获取的的policy
									'OSSAccessKeyId': res[1].data.data.accessid, // 输入你的AccessKeyId
									'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
									'signature': res[1].data.data.signature // 输入你获取的的signature
								},
								header: {
									"Content-Type": "multipart/form-data",
									authentication : token
								},
								success: (uploadFileRes) => {
									let key = store.state.globalupApi + fileList
									let breviary = store.state.globalupApi + fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
									let square = store.state.globalupApi + fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
									pathList.splice(i, 0, {
										type: 0,
										key: key,
										breviary: breviary,
										square: square
									})
									if (pathList.length == tempFilePaths.length) {
										resolve(pathList)
										uni.hideLoading();
									}
								}
							})
						})
				}
			}
		});
	})
}
/**
 * 上传图片 阿里oss方式 h5
 */
export const uploadImageH5 = (event) => {
	return new Promise((resolve, reject) => {
		console.log('uploadImageH5',)
		const token = uni.getStorageSync('token')
		var pathList = [];
		uni.chooseImage({
			count: event.count || 9,
			success: (chooseImageRes) => {
				
				const tempFilePaths = chooseImageRes.tempFilePaths;
				const tempFiles = chooseImageRes.tempFiles;
				uni.showLoading({
					title: '上传中'
				})
				let obj = new Date()
				let day = obj.getDate()
				let month = obj.getMonth() + 1
				let year = obj.getFullYear()
				for (let i = 0; i < tempFilePaths.length; i++) {
					
					let index = tempFiles[i].name.lastIndexOf(".")
					let suffix = tempFiles[i].name.substr(index + 1)
					let fileList =  Math.random().toString(36).substr(2) +
						'.' + suffix
						console.log('tempFilePaths[i]',tempFilePaths[i])
					
					uni.request({   
							url: api + 'api/upload/get_sign',
							data: {
							},
							method: 'POST',
							header: {
								"Content-Type": store.state.requestHeader,
								Authentication : token
							},
						})
						.then((res) => {
							// console.log('res',res)
							uni.uploadFile({
								url: res[1].data.data.host,
								filePath: tempFilePaths[i],
								name: event.name ? event.name : 'file',
								formData: {
									'key': fileList,
									'policy': res[1].data.data.policy, // 输入你获取的的policy
									'OSSAccessKeyId': res[1].data.data.accessid, // 输入你的AccessKeyId
									'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
									'signature': res[1].data.data.signature // 输入你获取的的signature
								},
								header: {
									Authentication : token
								},
								success: (uploadFileRes) => {
									// console.log('uploadFileRes',uploadFileRes)
									let key = res[1].data.data.host+ fileList
									let breviary = res[1].data.data.host + fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
									let square = res[1].data.data.host + fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
										
									pathList.splice(i, 0, {
										type: 0,
										key: key,
										breviary: breviary,
										square: square
									})
									console.log('上传成功',pathList)
									if (pathList.length == tempFilePaths.length) {
										resolve(pathList)
										uni.hideLoading();
									}
								},
								fail:(err)=>{
									console.log('上传失败',err)
								}
							})
						})
				}
			},
			fail(e) {
				console.log('eeeeeee',e)
			}
			
		});
	})
}

export const uploadFileH5 = (event) => {
	return new Promise((resolve, reject) => {
		console.log('uploadImageH5',)
		const token = uni.getStorageSync('token')
		var pathList = [];
		uni.chooseFile({
			count: event.count || 9,
			success: (chooseImageRes) => {
				console.log('chooseImageRes',chooseImageRes)
				const tempFilePaths = chooseImageRes.tempFilePaths;
				const tempFiles = chooseImageRes.tempFiles;
			
				uni.showLoading({
					title: '上传中'
				})
				let obj = new Date()
				let day = obj.getDate()
				let month = obj.getMonth() + 1
				let year = obj.getFullYear()
				for (let i = 0; i < tempFilePaths.length; i++) {
					let realName = tempFiles[i].name
					let index = tempFiles[i].name.lastIndexOf(".")
					let suffix = tempFiles[i].name.substr(index + 1)
					// let fileList =  Math.random().toString(36).substr(2) +
					// 	'.' + suffix
					let fileList = 	 Math.random().toString(36).substr(2) +
						'@' + realName
						console.log('fileList',fileList)
					
					uni.request({   
							url: api + 'api/upload/get_sign',
							data: {
							},
							method: 'POST',
							header: {
								"Content-Type": store.state.requestHeader,
								Authentication : token
							},
						})
						.then((res) => {
							// console.log('res',res)
							uni.uploadFile({
								url: res[1].data.data.host,
								filePath: tempFilePaths[i],
								name: event.name ? event.name : 'file',
								formData: {
									'key': fileList,
									'policy': res[1].data.data.policy, // 输入你获取的的policy
									'OSSAccessKeyId': res[1].data.data.accessid, // 输入你的AccessKeyId
									'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
									'signature': res[1].data.data.signature // 输入你获取的的signature
								},
								header: {
									Authentication : token
								},
								success: (uploadFileRes) => {
									// console.log('uploadFileRes',uploadFileRes)
									let key = res[1].data.data.host+ fileList
									let breviary = res[1].data.data.host + fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
									let square = res[1].data.data.host + fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
										
									pathList.splice(i, 0, {
										type: 0,
										key: key,
										breviary: breviary,
										square: realName
									})
									console.log('上传成功',pathList)
									if (pathList.length == tempFilePaths.length) {
										resolve(pathList)
										uni.hideLoading();
									}
								},
								fail:(err)=>{
									console.log('上传失败',err)
								}
							})
						})
				}
			},
			fail(e) {
				console.log('eeeeeee',e)
			}
			
		});
	})
}

export const uploadVideo = (event) => {
	return new Promise((resolve, reject) => {
		console.log('uploadImageH5',)
		const token = uni.getStorageSync('token')
		var pathList = [];
		uni.chooseVideo({
			count: event.count || 9,
			success: (chooseImageRes) => {
				console.log('chooseImageRes',)
				const tempFilePaths = [chooseImageRes.tempFilePath];
				const tempFiles = [chooseImageRes.tempFile];
				uni.showLoading({
					title: '上传中'
				})
				let obj = new Date()
				let day = obj.getDate()
				let month = obj.getMonth() + 1
				let year = obj.getFullYear()
				for (let i = 0; i < tempFilePaths.length; i++) {
					
					let index = tempFiles[i].name.lastIndexOf(".")
					let suffix = tempFiles[i].name.substr(index + 1)
					let fileList =  Math.random().toString(36).substr(2) +
						'.' + suffix
						console.log('tempFilePaths[i]',tempFilePaths[i])
					
					uni.request({   
							url: api + 'api/upload/get_sign',
							data: {
							},
							method: 'POST',
							header: {
								"Content-Type": store.state.requestHeader,
								Authentication : token
							},
						})
						.then((res) => {
							// console.log('res',res)
							uni.uploadFile({
								url: res[1].data.data.host,
								filePath: tempFilePaths[i],
								name: event.name ? event.name : 'file',
								formData: {
									'key': fileList,
									'policy': res[1].data.data.policy, // 输入你获取的的policy
									'OSSAccessKeyId': res[1].data.data.accessid, // 输入你的AccessKeyId
									'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
									'signature': res[1].data.data.signature // 输入你获取的的signature
								},
								header: {
									Authentication : token
								},
								success: (uploadFileRes) => {
									console.log('uploadFileRes',uploadFileRes)
									let key = res[1].data.data.host+ fileList
									let breviary = res[1].data.data.host + fileList +
										'?x-oss-process=video/snapshot,t_1000,f_jpg'
									let square = res[1].data.data.host + fileList +
										'?x-oss-process=video/snapshot,t_1000,f_jpg'	
									pathList.splice(i, 0, {
										type: 0,
										key: key,
										breviary: breviary,
										square: square
									})
									console.log('上传成功',pathList)
									if (pathList.length == tempFilePaths.length) {
										resolve(pathList)
										uni.hideLoading();
									}
								},
								fail:(err)=>{
									console.log('上传失败',err)
								}
							})
						})
				}
			},
			fail(e) {
				console.log('eeeeeee',e)
			}
			
		});
	})
}

/**
 * 上传视频
 */
export const uploadVideo2 = (event) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('userInfo').token
		var video = []
		uni.chooseVideo({
			count: 1,
			success: (chooseVideoRes) => {
				const tempFilePath = chooseVideoRes.tempFilePath;
				console.log('tempFilePath',tempFilePath)
				uni.showLoading({
					title: '上传中'
				})
				let obj = new Date()
				let day = obj.getDate()
				let month = obj.getMonth() + 1
				let year = obj.getFullYear()
				// for (let i = 0; i < tempFilePath.length; i++) {
				let index = tempFilePath.lastIndexOf(".")
				let suffix = tempFilePath.substr(index + 1)
				let fileList = year + '/' + month + '/' + day + Math.random().toString(32).substr(2) +
					'.' + suffix
					
							
					
				uni.request({
						url: api + 'api/upload/get_sign',
					data: {
						token: token
					},
					method: 'POST',
					header: {
						"Content-Type": "application/json"
					},
					success: (res) => {
						console.log('key',fileList)
						console.log('policy',res.data.data.host)
							console.log('OSSAccessKeyId',res.data.data.accessid)
								console.log('signature',res.data.data.signature)
						
								
						uni.uploadFile({
							url: res.data.data.host,
							filePath: tempFilePath,
							name: event.name ? event.name : 'file',
							formData: {
								'key': fileList,
								'policy': res.data.data.policy, // 输入你获取的的policy
								'OSSAccessKeyId': res.data.data.accessid, // 输入你的AccessKeyId
								'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
								'signature': res.data.data.signature // 输入你获取的的signature
							},
							header: {
								"Content-Type": store.state.requestHeader,
									Authentication : token
							},
							success: (uploadFileRes) => {
								let key = res.data.data.host + fileList
								let breviary = res.data.data.host + fileList +
									'?x-oss-process=video/snapshot,t_1000,f_jpg'
								let square = res.data.data.host + fileList +
									'?x-oss-process=video/snapshot,t_1000,f_jpg'
									
								pathList.splice(i, 0, {
									type: 0,
									key: key,
									breviary: breviary,
									square: square
								})	
									
								video.push({
									type: 1,
									key: key,
									breviary: breviary,
									square: square
								})
								resolve(video);
								console.log('video',video);
							}
						});
					}
				})
			}
		});
	})
}
/**
 * 不调起相册的上传图片方法 小程序
 */
export const upimg = (event) => {
	return new Promise((resolve, reject) => {
		if (event.url) {
			let obj = new Date()
			let day = obj.getDate()
			let month = obj.getMonth() + 1
			let year = obj.getFullYear()
			let index = event.url.lastIndexOf(".");
			let suffix = event.url.substr(index + 1);
			let fileList = uni.getStorageSync('userinfo').id + '/' + Math.random().toString(36).substr(2) +
				'.' + suffix
			uni.request({
					url: api + 'oss_getSign',
					data: {
						token: token
					},
					method: 'POST',
					header: {
						"Content-Type": store.state.requestHeader
					},
				})
				.then((res) => {
					console.log('签名')
					console.log(res);
					uni.uploadFile({
						url: updateApi,
						filePath: event.url,
						name: event.name ? event.name : 'file',
						formData: {
							'key': fileList,
							'policy': res[1].data.data.policy, // 输入你获取的的policy
							'OSSAccessKeyId': res[1].data.data.accessid, // 输入你的AccessKeyId
							'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
							'signature': res[1].data.data.signature // 输入你获取的的signature
						},
						header: {
							"Content-Type": "multipart/form-data",
							"token": uni.getStorageSync('token')
						},
						success: (uploadFileRes) => {
							let key = updateApi + fileList;
							resolve(key)
							uni.hideLoading();
						}
					})
				})
		} else {
			console.error("请传入URL");
			reject(undefined);
		}
	});
}